package liuh.com.ledlamp.handle;

import android.content.Context;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import liuh.com.ledlamp.util.FileKit;

/**
 * @author :liuh
 * @note 显示内容；撤销内容；初始化分区池；显示内容缓存处理
 * @date: 2016-12-06
 */

public class DisTitle {

    private volatile static DisTitle mInstance;
    // 分区集合
    List<String> wids;
    // 控制屏显示的title
    Map<String, String> dis_title = new HashMap<String, String>();

    public static DisTitle getInstance() {
        if (mInstance == null) {
            synchronized (DisTitle.class) {
                if (mInstance == null) {
                    mInstance = new DisTitle();
                }
            }
        }
        return mInstance;
    }

    private DisTitle() {
        initWids();
    }

    /**
     * @note 初始化分区
     * @author liuh
     */
    private void initWids() {
        wids = new ArrayList<String>();
        wids.add("1");
        wids.add("2");
        wids.add("3");
        //
    }

    /**
     * @note 显示指定分区内容
     * @author liuh
     */
    public void disWid(String title, String wid, Context mContext) throws Exception {
        wids.remove(wid);
        dis_title.put(wid, title);
        // 数据保存
        new FileKit(mContext).saveObject(dis_title, "dis_title");
    }

    /**
     * @note 撤销显示指定分区内容
     * @author liuh
     */
    public void unDisWid(String wid, Context mContext) throws Exception {
        wids.add(wid);
        dis_title.remove(wid);
        // 数据保存
        new FileKit(mContext).saveObject(dis_title, "dis_title");
    }

    /**
     * @note 从分区集合中获取未分区的wid
     * @author liuh
     */
    public String getWidByWids(Map<String, String> dis_titleT) {
        String wid = "";
        if (wids.size() > 0) {
            for (int i = 0; i < wids.size(); i++) {
                wid = wids.get(i);
                if(!isUseWid(dis_titleT,wid)){
                    //该wid分区未使用
                    wids.remove(wid);
                    break;
                }else{
                    wid="";
                }
            }
        }
        return wid;
    }

    /**
     * @note 该分区是否使用
     * @author liuh
     * */
    private boolean isUseWid(Map<String, String> dis_titleT, String wid) {
        boolean result = false;
        if (dis_titleT != null) {
            if (dis_titleT.get(wid) != null) {
                result = true;
            }
        }
        return result;
    }

    /**
     * @note 根据title 获取wid
     * @author liuh
     */
    public String getKeyByValue(Map map, Object value) {
        String keys = "";
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object obj = entry.getValue();
            if (obj != null && obj.equals(value)) {
                keys = (String) entry.getKey();
                break;
            }
        }
        return keys;
    }
}
